package code.cando;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * author : yeswater
 * date : 2023/12/9
 * <p>
 * 合并区间
 * <p>
 * 合并所有重叠的区间  返回一个不重叠的区间数组
 */

public class T056 {
    public int[][] merge(int[][] intervals) {
        List<int[]> res = new ArrayList<>();
        // 按照左边界排序
        Arrays.sort(intervals, (a, b) -> a[0] - b[0]);
        int start = intervals[0][0];
        int right = intervals[0][1];
        for (int i = 1; i < intervals.length; i++) {
            // 左 > 右
            if (intervals[i][0] > right) {
                res.add(new int[]{start, right});
                start = intervals[i][0];
                right = intervals[i][1];
            } else {
                right = Math.max(right, intervals[i][1]);
            }
        }
        res.add(new int[]{start, right});
        return res.toArray(new int[res.size()][]);
    }
}
